package cn.imvc.app.models;

import java.util.Date;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.domains.OrderState;
import cn.imvc.app.domains.OrderType;
import cn.imvc.app.entities.DealerApply;
import cn.imvc.app.entities.Member;
import cn.imvc.app.entities.Recharge;
import cn.imvc.app.repositories.RechargeRepository;
import cn.imvc.data.domain.ViewRequest;
import cn.imvc.util.RandomId;

@Service
public class RechargeModelImpl implements RechargeModel {

	@Autowired
	private RechargeRepository rechargeRepository;
	
	@Autowired
	AccountModel accountModel;
	
	@Autowired
	MemberModel memberModel;

	public Recharge get(int id) {
		return rechargeRepository.findOne(id);
	}

	public Page<Recharge> find(ViewRequest viewRequest) {
		return (Page<Recharge>) rechargeRepository.findAll();
	}

	public Recharge save(Recharge recharge) {
		Recharge recharge2 = rechargeRepository.saveAndFlush(recharge);
		return recharge2;
	}

	public Recharge update(Recharge newRecharge) {
		Recharge loadRecharge = get(newRecharge.getId());
		BeanUtils.copyProperties(newRecharge, loadRecharge, new String[] { "id" });
		return rechargeRepository.saveAndFlush(loadRecharge);
	}

	public void delete(int id) {
		rechargeRepository.delete(id);
	}

	public void deleteBatch(int[] ids) {
		for (int id : ids) {
			delete(id);
		}
	}
	
	public Recharge saveRechargeOrder(Integer money,Member member){
		Recharge recharge=new Recharge();
		recharge.setMemberId(member.getId());
		recharge.setCreatedAt(new Date());
		recharge.setUpdatedAt(new Date());
		recharge.setMoney(money);
		recharge.setState(OrderState.Create.getValue());
		recharge.setCode(OrderType.Recharge.getValue()+RandomId.randomId(new Date().getTime()));
		
		return rechargeRepository.save(recharge);
	}
	
	public Recharge findByCode(String code){
		return rechargeRepository.findByCode(code);
	}
	
	public void finishPay(String code,String payCode,Date payTime){
		Recharge recharge=findByCode(code);
		if(recharge.getState()!=OrderState.Payment.getValue()){
			return;
		}
		Member member=memberModel.get(recharge.getMemberId());		
		recharge.setPayCode(payCode);
		recharge.setPayTime(payTime);
		recharge.setState(OrderState.PaySuccess.getValue());
		recharge.setUpdatedAt(new Date());
		save(recharge);
		accountModel.retrySaveAccount(member.getAccount().getId(), recharge.getMoney(), 0, 0);
		
	}
	
}
